package com.example.todolist;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.LauncherActivity;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.icu.text.SimpleDateFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends AppCompatActivity implements Runnable,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {

    public  static  final  String TAG="list";
    Handler handler;
    ListView listView;
    MyAdapter myAdapter;
    String UpDateStr;
    public void setHandler(Handler handler) {
        this.handler = handler;
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        UpDateStr = (new SimpleDateFormat("yyyy-MM-dd")).format(new Date());

        //绑定控件
        listView=findViewById(R.id.mylist);

        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);

        handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                //收到数据
                if(msg.what==5){
                    ArrayList<HashMap<String,String>> list= (ArrayList<HashMap<String, String>>) msg.obj;
//                    SimpleAdapter listItemAdapter = new SimpleAdapter(RateListActivity2.this,
//                            list,//数据源
//                            R.layout.list_item,//布局
//                            new String[]{"cname","cval"},
//                            new int[] {R.id.title,R.id.detail}
//                    );
//                    listView.setAdapter(listItemAdapter);
                    myAdapter=new MyAdapter(MainActivity.this,R.layout.list_item,list);
                    listView.setAdapter(myAdapter);
                }
                super.handleMessage(msg);
            }
        };
        //开启线程
        Thread t = new Thread(this);
        t.start();//myTask.run();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.add,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if(item.getItemId()==R.id.add){
            Intent intent=new Intent(this,AddActivity.class);
            startActivityForResult(intent,3);
        }
        if(item.getItemId()==R.id.my_menu){
            Intent intent=new Intent(this,HistoryActivity.class);
            startActivityForResult(intent,3);
        }

        return super.onOptionsItemSelected(item);
    }



    @Override

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
        //获得当前点击行数据
        HashMap<String,String> map=(HashMap<String,String>)listView.getItemAtPosition(position);
        Log.i(TAG,"onItemClick:title="+map.get("title"));
        Log.i(TAG,"onItemClick:detail="+map.get("detail"));
        Log.i(TAG,"onItemClick:position="+position);
        Log.i(TAG,"onItemClick:id="+map.get("id"));


        Integer _id=Integer.parseInt(map.get("id"));
        Log.i("id","获取id:"+_id);
        Intent intent=new Intent(this,DetailActivity.class);
        intent.putExtra("id",String.valueOf(_id));
        intent.putExtra("title",map.get("title"));
        intent.putExtra("detail",map.get("detail"));
        intent.putExtra("date",map.get("date"));
        intent.putExtra("position",position);
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
        Log.i(TAG,"onItemLongCLick:pos="+position);
        //删除数据处理
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示")
                .setMessage("请确认是否删除该数据")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.i(TAG,":onclick:对话框事件处理");

                        //获得当前点击行数据
                        HashMap<String,String> map=(HashMap<String,String>)listView.getItemAtPosition(position);
                        String id2=map.get("id");
                        Integer _id=Integer.parseInt(id2);
                        Log.i("id","获取id:"+_id);

                        DBManager dbManager = new DBManager(MainActivity.this);

                        dbManager.delete(_id);
                        myAdapter.remove(listView.getItemAtPosition(position));
                    }
                }).setNegativeButton("否",null);
        builder.create().show();

        return true;
    }


    @Override
    public void run() {


        ArrayList<HashMap<String, String>> retList = new ArrayList<HashMap<String, String>>();
        //List<String> retList=new ArrayList<String>();
        Log.i("List", "run...");


        Log.i("run", "修改时间:" + UpDateStr);
        Log.i("run", "从数据库中获取数据显示");
        DBManager dbManager = new DBManager(MainActivity.this);

        Boolean len = dbManager.listAll().isEmpty();
        Log.i("run", "是否为空" + len);

        if (len) {
            ListItem listItem = new ListItem();
            listItem.setTitle("开始记事吧");
            listItem.setDetail("详情");
            listItem.setDate(UpDateStr);
            listItem.setSituation("未完成");
            listItem.setDdl(UpDateStr);

            dbManager.add(listItem);
        }
        Log.i("run","add") ;
        for (ListItem listItem : dbManager.listAll()) {
            //构造map放入数据
            HashMap<String, String> map = new HashMap<String, String>();

            if(listItem.getSituation().equals("未完成")) {
                Log.i("run", "id" + listItem.getId());
                Log.i("run", "title" + listItem.getTitle());
                Log.i("run", "detail" + listItem.getDetail());
                Log.i("run", "date" + listItem.getDate());
                Log.i("run", "situation" + listItem.getSituation());
                map.put("id", String.valueOf(listItem.getId()));
                map.put("title", listItem.getTitle());   //标题文字
                map.put("detail", listItem.getDetail());//详情描述
                map.put("date", listItem.getDate());//修改时间
                map.put("situation", listItem.getSituation());//完成情况
                map.put("ddl", listItem.getDdl());//ddl
                retList.add(map);
            }
        }
        //返回消息给主线程
        //获取MSG对象,收件人：5
        Message msg = handler.obtainMessage(5);
        //内容
        msg.obj = retList;
        handler.sendMessage(msg);
        Log.i(TAG, "sendmsg ok");

    }
}